package com.getpebble.android.framework.protocol.outbound;

import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.util.ByteUtils;

public class PblOutboundPhoneControlMessage extends PblOutboundMessage {
    private String mCallerName;
    private String mCallerNumber;
    private PhoneControlCommand mCommand;
    private byte[] mCookie;

    public enum PhoneControlCommand {
        UNKNOWN((byte) 0),
        ANSWER((byte) 1),
        HANGUP((byte) 2),
        GET_STATE((byte) 3),
        INCOMING_CALL((byte) 4),
        OUTGOING_CALL((byte) 5),
        MISSED_CALL((byte) 6),
        RING((byte) 7),
        START((byte) 8),
        END((byte) 9);
        
        private byte command;

        private PhoneControlCommand(byte command) {
            this.command = command;
        }

        public byte getCommand() {
            return this.command;
        }
    }

    public PblOutboundPhoneControlMessage(PhoneControlCommand command, byte[] cookie) {
        super(EndpointId.PHONE_CONTROL);
        if (commandRequiresDetails(command)) {
            throw new IllegalArgumentException("Command " + command + " requires the caller's name and number.");
        }
        this.mCommand = command;
        this.mCookie = cookie;
    }

    public PblOutboundPhoneControlMessage(PhoneControlCommand command, byte[] cookie, String callerNumber, String callerName) {
        super(EndpointId.PHONE_CONTROL);
        this.mCommand = command;
        this.mCookie = cookie;
        this.mCallerNumber = callerNumber;
        this.mCallerName = callerName;
    }

    private boolean commandRequiresDetails(PhoneControlCommand command) {
        return command.equals(PhoneControlCommand.INCOMING_CALL) || command.equals(PhoneControlCommand.MISSED_CALL);
    }

    public synchronized byte[] getBytes() {
        if (!areBytesCached()) {
            addBytes(Byte.valueOf(this.mCommand.getCommand()));
            addBytes(this.mCookie);
            if (commandRequiresDetails(this.mCommand)) {
                ByteUtils.writePascalString(this, this.mCallerNumber, 255);
                ByteUtils.writePascalString(this, this.mCallerName, 255);
            }
        }
        return super.getBytes();
    }
}
